/// <reference path="../obs.d.ts" />
import { Request, Response } from 'express';
import OBS from 'esdk-obs-nodejs';
import dotenv from 'dotenv';
import path from 'path';
import fs from 'fs';

dotenv.config();

// 初始化 OBS 客户端
const obsClient = new OBS({
    access_key_id: process.env.HUAWEI_CLOUD_ACCESS_KEY || '',
    secret_access_key: process.env.HUAWEI_CLOUD_SECRET_KEY || '',
    server: `https://obs.${process.env.HUAWEI_CLOUD_REGION}.myhuaweicloud.com`,
});

// 上传文件到 OBS 的函数
const uploadFileToObs = async (filePath: string, destFileName: string): Promise<string> => {
    return new Promise((resolve, reject) => {
        obsClient.putObject(
            {
                Bucket: process.env.HUAWEI_CLOUD_BUCKET_NAME || '',
                Key: destFileName,
                SourceFile: filePath,
            },
            (err: any, result: any) => {
                // 删除临时文件
                fs.unlinkSync(filePath);

                if (err) {
                    console.error('err:', err);
                    reject(err);
                } else if (result.CommonMsg.Status < 300) {
                    // 构建包含桶名称的正确 URL
                    const bucketName = process.env.HUAWEI_CLOUD_BUCKET_NAME;
                    const region = process.env.HUAWEI_CLOUD_REGION;
                    const fileUrl = `https://${bucketName}.obs.${region}.myhuaweicloud.com/${destFileName}`;

                    console.log(`文件上传成功. URL: ${fileUrl}`);
                    resolve(fileUrl);
                } else {
                    console.error('FailedStatus:', result.CommonMsg.Status);
                    reject(new Error(`FailedStatus: ${result.CommonMsg.Status}`));
                }
            }
        );
    });
};


// 控制器处理文件上传请求
export const uploadFile = async (req: Request, res: Response): Promise<void> => {
    console.log('上传文件')
    try {
        if (!req.file) {
            res.status(400).json({ message: '没有文件！' });
            return;
        }
        const filePath = req.file.path;
        const destFileName = `uploads/${Date.now()}_${path.basename(req.file.originalname)}`;
        const fileUrl = await uploadFileToObs(filePath, destFileName);
        res.json({ message: '文件上传成功', url: fileUrl });
    } catch (error) {
        console.error('文件上传错误:', error);
        res.status(500).json({ message: '文件上传错误', error });
    }
};
